package com.rkc.mq;

import com.rabbitmq.client.Channel;
import com.rkc.model.ProductMessage;
import com.rkc.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author `RKC`
 * @date 2021/11/9 16:41
 */
@Slf4j
@Component
@RabbitListener(queues = "${mqconfig.stock_release_queue}")
public class ProductStockMQListener {

    @Autowired
    private ProductService productService;

    @RabbitHandler
    public void releaseProductStock(ProductMessage productMessage, Channel channel, Message message) {
        log.info("监听到消息，releaseProductStock：{}", productMessage);
        try {
            if (productService.releaseProductStock(productMessage)) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                log.info("商品库存释放成功 {}", productMessage);
            } else {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
                log.error("商品库存释放失败 {}", productMessage);
            }
        } catch (IOException e) {
            log.info("商品库存释放异常 {}", productMessage);
        }
    }
}
